<template>
	<view class="pages">
		<view>
			<view class="u-font-28 color333 flex align-center">
				<view class="edit u-m-r-10">
					<u-icon name="edit-pen" size="36" color="#ffffff"></u-icon>
				</view>
				输入合集名称
			</view>
			<view class="u-font-24 color999 u-m-l-50">建议选择公共名称，可产生链接，让更多的用户看到</view>
		</view>
		<view class="bg-white inputChange u-m-t-20 flex u-p-l-20 u-p-r-20">
			<u-input class="u-flex-1 u-font-28" :clearable="false" placeholder=" " v-model="keyWord"></u-input>
		</view>

		<!-- 关键词 -->
		<view class="u-m-t-30 key-box">
			<view class="flex align-center u-m-b-30">
				<view class="add-key" @click="addKey">+关键词</view>
				<view class="u-font-24 color999 u-m-l-20">最多可以添加5个，每个不超过20个字符</view>
			</view>
			<view class="flex align-center flex-wrap">
				<view class="tag-item bg-white flex align-center justify-between" v-for="(item,index) in tagList" :key="index">
					{{item.name}}
					<u-icon @click="delTag(index)" class="u-m-l-10" name="close" size="20" color="#7F7F7F"></u-icon>
				</view>
			</view>
		</view>

		<!-- 公共名字 -->
		<view class="u-m-t-30">
			<view class="flex align-center">
				<u-icon
					name="https://aihelp.oss-cn-hangzhou.aliyuncs.com/public/base/2023/11/22/c9bebc8f61a14659941439afefe7724d.png"
					size="40"></u-icon>
				<view class="color333 bold u-font-28 u-m-l-5">公共名字</view>
				<view class="u-font-24 color999 u-m-l-5">（点文字选中，点小图标看关键词）</view>
			</view>
			<view class="flex align-center flex-wrap">
				<view class="u-m-r-35 bg-white u-p-10 flex align-center justify-center u-font-28 u-m-t-20"
					@click="handleSelect(item)" v-for="(item,index) in list" :key="index">
					{{item.name}}
					<view @click.stop="handleOpenTags(item)">
						<u-icon class="u-m-l-20" name="tags-fill" color="#000" size="28"></u-icon>
					</view>
				</view>
			</view>
			<view class="u-p-b-30 u-p-t-30" v-if="list && list.length">
				<u-loadmore @loadmore="handleListBottom" font-size="24" color="#999" :status="status" />
			</view>
		</view>

		<!-- 底部按钮 -->
		<view class="flex align-center justify-center know-btns" :style="'padding-bottom:'+safeAreaInsetsBottom+'px;'">
			<view class="submit" @click="submit">确定创建</view>
		</view>
		<u-select @cancel="cancel" confirm-text="确认更换" cancel-color="#333" :mask-close-able="false" confirm-color="#333"
			cancel-text="不更换" safe-area-inset-bottom title="已有相似名称,请选择" v-model="show" mode="single-column" :list="selectList"
			@confirm="handleSelect">
			<u-icon class="u-m-l-10" slot="titleSolt"
				name="https://aihelp.oss-cn-hangzhou.aliyuncs.com/public/base/2023/11/23/caa2ade34bc64623b674585a04caa628.png"
				size="64"></u-icon>
		</u-select>
		<u-popup closeable :mask-close-able="false" mode="center" v-model="keyShow" border-radius="24" width="80%">
			<view class="u-p-b-60 u-p-l-30 u-p-r-30">
				<view class="text-center u-font-32 bold color333 u-m-t-30 u-m-b-40">新增关键词</view>
				<u-input v-model="tagWord" type="textarea" :maxlength="20" border placeholder="请输入关键词,不超过20个字符"></u-input>
				<view class="add-key-word" @click="handleAddKeyWord">
					新增
				</view>
			</view>
		</u-popup>
		<u-popup closeable mode="center" v-model="lookKeys" border-radius="24" width="80%">
			<view class="u-p-30">
				<view class="text-center u-font-28 u-m-b-40">合集名称：<text class="bold u-font-30">{{openKeys.name}}</text> </view>
				<view class="flex align-center flex-wrap" v-if="openKeys.keyWords && openKeys.keyWords.length">
					<view class="tags-item" v-for="(item,index) in openKeys.keyWords" :key="index">{{item}}</view>
				</view>
				<view v-else class="flex align-center justify-center u-font-28 color999">无关键词</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		treeSave,
		treeUpdate,
		treeGet,
		TreePublicQuery,
		findTreePrivate
	} from "@/api/send.js";
	export default {
		data() {
			return {
				status:'loadmore',
				publicObj: {},
				openKeys: {},
				lookKeys: false,
				page: 1,
				size: 12,
				isEdit: false,
				tagList: [],
				tagWord: "",
				keyShow: false,
				safeAreaInsetsBottom: 0,
				selectList: [],
				show: false,
				keyWord: "",
				list: [],
				subject: null
			}
		},
		async onLoad(e) {
			await this.hanldeGetStorage();
			// 查询公有知识树
			this.getPublicTree();
			if (e.key) {
				this.isEdit = true;
				this.keyWord = JSON.parse(JSON.stringify(this.subject.collectionName));
				this.getData();
				uni.setNavigationBarTitle({
					title: "修改合集"
				})
			}
			this.$nextTick(() => {
				this.safeAreaInsetsBottom = this.$u.sys().safeAreaInsets.bottom;
			})
		},
		methods: {
			//加载更多
			handleListBottom(){
				if(this.status === 'nomore') return;
				this.page++;
				this.status = 'loading';
				this.getPublicTree();
			},
			//选择公有名称
			handleSelect(e) {
				this.publicObj = e;
				this.keyWord = e.name;
				this.confirm(true);
			},
			//点击查看公共名字的关键词
			handleOpenTags(row) {
				this.openKeys = row;;
				this.lookKeys = true;
			},
			//获取本地数据
			hanldeGetStorage() {
				if (uni.getStorageSync('subject')) {
					this.subject = JSON.parse(uni.getStorageSync('subject'));
				}
			},
			//查询公有知识树
			getPublicTree() {
				uni.showLoading({
					mask: true
				});
				TreePublicQuery({
					subjectCode2: this.subject.subjectCode2,
					subjectName2: this.subject.subjectName2,
					page: this.page,
					size: this.size,
					treeName: "",
					treeType: 0
				}).then(res => {
					if (res.code == 100000) {
						if (this.page == 1) {
							this.list = [];
						}
						if (res.data && res.data.list && res.data.list.length) {
							let arr = res.data.list.map(e => {
								return {
									name: e.treeName,
									id: e.id,
									keyWords: e.keyWords ? e.keyWords.split(',') : []
								}
							})
							this.list.push(...arr);
						}
						if (Number(res.data.tatol) <= this.list.length) {
							this.status = 'nomore';
						} else {
							this.status = 'loadmore';
						}
					}
				}).finally(()=>{
					uni.hideLoading();
				})
			},
			getData() {
				treeGet(this.subject.collectionId).then(res => {
					if (res.code == 100000) {
						if (res.data.keyWords) {
							this.tagList = res.data.keyWords.split(',').map(e => {
								return {
									name: e
								}
							})
						}
					}
				})
			},
			//删除标签
			delTag(i) {
				this.tagList.splice(i, 1);
			},
			//新增关键词
			handleAddKeyWord() {
				this.tagList.push({
					name: this.tagWord
				})
				this.keyShow = false;
			},
			//添加关键词
			addKey() {
				this.tagWord = "";
				this.keyShow = true;
			},
			//不更换
			cancel() {
				this.confirm();
			},
			//更换
			confirm(isCheck = false) {
				// 创建合集后自动为用户创建第一章和第一节
				if (uni.getStorageSync('subject')) {
					let keyWords = "";
					if (this.tagList && this.tagList.length) {
						keyWords = this.tagList.map(e => e.name).join(',');
					}
					if (isCheck) {
						keyWords = this.publicObj.keyWords.join(',');
					}
					let data = {
						parentId: 0,
						treePrivateState: 1,
						treePrivateName: this.keyWord,
						type: 0, //合集
						subjectCode: this.subject.subjectCode,
						subjectCode2: this.subject.subjectCode2,
						subjectName: this.subject.subjectName,
						subjectName2: this.subject.subjectName2,
						keyWords: keyWords,
					}
					let str = "合集创建成功!";
					data['treePublicId'] = isCheck ? this.publicObj.id : '';
					data['treePublicName'] = isCheck ? this.publicObj.name : '';
					uni.showLoading({
						mask: true
					});
					if (this.isEdit) {
						data['id'] = this.subject.collectionId;
						str = "合集修改成功!";
						if (this.subject.collectionName == this.keyWord) {
							treeUpdate(data).then(res => {
								if (res.code == 100000) {
									uni.showToast({
										title: str,
										icon: 'none'
									});
									uni.removeStorageSync('subject');
									setTimeout(() => {
										uni.navigateBack(1);
									}, 1000)
								}
							}).finally(() => {
								uni.hideLoading();
							})
						} else {
							findTreePrivate(this.subject.collectionId).then(obj => {
								if (obj.code == 100000) {
									let info = obj.data;
									for (let key in data) {
										info[key] = data[key];
									}
									treeSave(info).then(res => {
										if (res.code == 100000) {
											uni.showToast({
												title: str,
												icon: 'none'
											});
											uni.removeStorageSync('subject');
											setTimeout(() => {
												uni.navigateBack(1);
											}, 1000)
										}
									}).finally(() => {
										uni.hideLoading();
									})
								}
							})
						}
					} else {
						treeSave(data).then(res => {
							if (res.code == 100000) {
								uni.showToast({
									title: str,
									icon: 'none'
								});
								uni.setStorageSync('subject', JSON.stringify({
									...this.subject,
									collectionName: this.keyWord,
									collectionId: res.data
								}))
								setTimeout(() => {
									uni.redirectTo({
										url: `/pages/send/knowledge/knowledgeCreateChapter/knowledgeCreateChapter`,
									});
								}, 1000)
							}
						}).finally(() => {
							uni.hideLoading();
						})
					}
				}
			},
			submit() {
				if (!this.keyWord) {
					uni.showToast({
						title: '合集名称不能为空！',
						icon: 'none'
					});
					return;
				}
				uni.showLoading({
					mask: true
				});
				TreePublicQuery({
					subjectCode2: this.subject.subjectCode2,
					subjectName2: this.subject.subjectName2,
					page: 1,
					size: 30,
					treeName: this.keyWord,
					treeType: 0
				}).then(res => {
					if (res.code == 100000) {
						if (res.data.list && res.data.list.length) {
							this.selectList = res.data.list.map(e => {
								return {
									value: e.id,
									label: e.treeName
								}
							})
							this.show = true;
						} else {
							this.confirm();
						}
					}
				}).finally(() => {
					uni.hideLoading();
				})
			},
			//自动为用户创建第一章
			createFirstChapter(id) {
				let data = {
					parentId: id,
					treePrivateState: 1,
					treePrivateName: '第一章',
					type: 1, //章
					subjectCode: this.subject.subjectCode,
					subjectCode2: this.subject.subjectCode2,
					subjectName: this.subject.subjectName,
					subjectName2: this.subject.subjectName2
				}
				treeSave(data).then(res => {
					if (res.code == 100000) {
						this.createFirstJoint(res.data);
					}
				})
			},
			//自动为用户创建第一节
			createFirstJoint(id) {
				let data = {
					parentId: id,
					treePrivateState: 1,
					treePrivateName: '第一节',
					type: 2, //章
					subjectCode: this.subject.subjectCode,
					subjectCode2: this.subject.subjectCode2,
					subjectName: this.subject.subjectName,
					subjectName2: this.subject.subjectName2,
				}
				treeSave(data).then(res => {
					if (res.code == 100000) {

					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.pages {
		background-color: #F6F8F6;
		min-height: 100vh;
		padding: 40rpx 30rpx;

		.edit {
			background-color: #000;
			width: 40rpx;
			height: 40rpx;
			border-radius: 8rpx;
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.inputChange {
			height: 84rpx;
		}

		.key-box {
			min-height: 248rpx;
			border-bottom: 2rpx solid #000;

			.tag-item {
				border-radius: 100rpx;
				height: 64rpx;
				padding-left: 20rpx;
				padding-right: 20rpx;
				font-size: 28rpx;
				color: #7F7F7F;
				margin-right: 36rpx;
				margin-bottom: 10rpx;
			}

			.add-key {
				background-color: #333;
				font-size: 24rpx;
				color: #F7DD5E;
				width: 134rpx;
				height: 60rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				border-radius: 100rpx;
			}
		}

		.know-btns {
			position: fixed;
			left: 50%;
			transform: translate(-50%);
			font-size: 28rpx;
			height: 90rpx;
			line-height: 90rpx;
			text-align: center;
			bottom: 60rpx;

			.close {
				border-radius: 100rpx 0 0 100rpx;
				background-color: #72819A;
				width: 300rpx;
			}

			.submit {
				border-radius: 100rpx;
				color: #333;
				background-color: #F7DD5E;
				width: 600rpx;
			}
		}
	}

	.add-key-word {
		background-color: #F7DD5E;
		border-radius: 100rpx;
		width: 300rpx;
		height: 90rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 30rpx auto 0;
	}

	.tags-item {
		border: 2rpx solid #7F7F7F;
		border-radius: 100rpx;
		height: 54rpx;
		padding-left: 20rpx;
		padding-right: 20rpx;
		font-size: 24rpx;
		color: #7F7F7F;
		margin-right: 36rpx;
		margin-bottom: 10rpx;
		line-height: 54rpx;
	}
</style>